/*@Author S.Genikhov
/*Creation Date 8/06/2010
/*Last modifed 8/07/2010
/*@Brief the most usabale bit vector commands:SET and GET implementation */
#include <stdio.h>
#include <stdlib.h>
#include <bitvector.h>

#define ISBITSET(bv,i) (bv[i>>3] & (1<<(i& 0x07)))
#define SETBIT(bv,i) bv[i>>3]|=(1<<(i&(0x07)))
#define CLEARBIT(bv,i) bv[i>>3]&=~(1<<(i&(0x07)))
#define SIZE (100)
#define I (16)

void Bitv_ClearBit(unsigned char *bv,size_t index)
{
    CLEARBIT(bv,index);
    return;
}

void Bit_Set(unsigned char *bv,size_t index)
{
        SETBIT(bv,index);
    return;
}

/**********************************************************************************/
unsigned char*Bit_Createvector(size_t bitvectorsize)
{size_t size=bitvectorsize;

    (size%8)? (size=size/8+1) : (size=size/8);
    return (unsigned char*)calloc(size,sizeof(char));
}

/******************************************************************************/
void Bit_Destroivector(void* bv)
{
    free(bv);
}

/***********************************************************************/
void Bit_Getvalue(unsigned char* bv,unsigned char* a,size_t index,size_t nbits)
{
    int             i;
    *a=0;
    if (nbits>8)
    {
        nbits=8;
    }
    for(i=index;i<index+nbits;++i)
    {
        if(ISBITSET(bv,(i))>>(i&0x07))
        {
            SETBIT(a,(i-index));
        }
        else
        {
            CLEARBIT(a,(i-index));
        }
    }
}
/***********Testing**********************************************/
#ifdef Bit_unitests
size_t  unitest_bit();
size_t  test_getValue();
void    test_SetandGetandClear();
int main()
{
    unitest_bit();
    return 0;
}

size_t unitest_bit()
{
    size_t err;
    err=test_getValue();
    test_SetandGetandClear();
    return 0;
}

size_t test_getValue()
{
    unsigned char  *bv;
    unsigned char    a;
    size_t      result=0;
    bv=Bit_Createvector(SIZE);
    bv[2]=0x41;/*01000001*/
    bv[3]=0xA9;/*10101001*/

    Bit_Getvalue(bv,&a,16,8);
    if(65==a)
    {
        ++result;
    }
    Bit_Getvalue(bv,&a,24,8);
    if(169==a)
    {
        ++result;
    }
    2==result ? printf("Funciotn works ok"):printf("Wrong caclulations");
    return result;
}

void    test_SetandGetandClear()
{
    unsigned char  *bv;
    unsigned char    a;
    bv=Bit_Createvector(SIZE);
   /* bv[2]=0x41;/*01000001*/
   bv[0]=255;

   /* Bit_Set(bv,1);
    Bit_Set(bv,7);*/
    Bit_Getvalue(bv,&a,0,8);
    Bitv_ClearBit(&a,0);
    Bitv_ClearBit(&a,2);
    Bitv_ClearBit(&a,7);
    return;
}




#endif /*Bit_Test*/
